/**
 * 
 */
package com.myhouse.aspect;

import java.io.Serializable;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.alibaba.fastjson.JSON;

/**
 * @author Administrator
 * @date 2019年5月30日
 */
@ControllerAdvice
public class RestControllerResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
            ServerHttpResponse response) {
        // 对body进行封装处理
        if (body instanceof String) {
            String msg = (String) body;
            ResultJson resultJson = new ResultJson("-1", msg);
            // 因为在controller层中返回的是String类型，这边如果换成ResultJson的话，会导致StringMessageConverter方法类型转换异常，所以这边将对象转成字符串
            return JSON.toJSONString(resultJson);
        } else if (body instanceof Object) {
            Object data = (Object) body;
            ResultJson resultJson = new ResultJson(data);
            return resultJson;
        }
        return body;
    }
}



/**
 * 
 * 功能描述： 前后端数据交互统一的类
 */
class ResultJson implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    // 状态码 正确为0
    private String code = "0";
    // 错误描述
    private String msg = "";
    // 返回对象
    private Object data = "";

    public ResultJson() {
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public ResultJson(String code) {
        this.code = code;
    }

    public ResultJson(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public ResultJson(Object data) {
        this.data = data;
    }

    public ResultJson(String code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

}
